package com.py.credit.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.py.credit.common.XypjConstants;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.CheckReport;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.ResultObj;
import com.py.credit.entity.enums.ResourceCheckReportFieldsEnum;
import com.py.credit.service.CheckReportService;
import com.py.credit.service.GatewayAuthenticationService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.FileUtil;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 在线申请核查报告controller
 */
@Controller
@RequestMapping(value = "/checkReport")
public class CheckReportController {
	
	private final static String FRONT_TABLE_ID = "checkReport";

	@Autowired
	private CheckReportService checkReportService;
	
	@Autowired
	private GatewayAuthenticationService gatewayAuthenticationService;

	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Value("${absolutepath}")
	private String absolutepath;

	/**
	 * 新增一个在线申请核查报告工作流
	 * @param applicant_unit 企业名称
	 * @param check_purpose 核查用途
	 * @param user_id 用户id
	 * @param username 用户名称
	 * @return
	 */
	@RequestMapping(value = "/add.do")
	@ResponseBody
	public Object add(@RequestParam(value = "applicant_unit", defaultValue = "", required = true) String applicant_unit,
			@RequestParam(value = "check_purpose", defaultValue = "", required = true) String check_purpose,
			@RequestParam(value = "user_id", defaultValue = "", required = true) String user_id,
					  @RequestParam(value = "username", defaultValue = "", required = true) String username) {
		//登录超时不让添加
		if(null==user_id || user_id.equals("") || user_id.equals("-1")){
			ResultObj resultObj = new ResultObj(ResultObj.ERR_NO_LOGIN, "登录超时");

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("resultObj", resultObj);
			return map;
		}

		String tybm=checkReportService.selectTybmByQymc(applicant_unit);
		if(null==tybm || tybm.equals("")){
			ResultObj resultObj = new ResultObj(ResultObj.ERR_NO_LOGIN, "暂无企业数据");

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("resultObj", resultObj);
			return map;
		}

		Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String applicat_date = format.format(new Date());

		int id = checkReportService.addApplicationInfo(applicant_unit,tybm,check_purpose,applicat_date,Integer.parseInt(user_id),username);
		String accessKey = UuidUtil.getInstance().getUUid();

		xypjRemoteBaseService.addWorkFlow("resourceApplication",accessKey,0+"",null,id+"",
				"“" + applicant_unit + "”核查报告申请","","7",null);

		ResultObj resultObj = new ResultObj(ResultObj.SUCCESS);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("resultObj", resultObj);
		return map;
	}

	/**
	 * 工作流页面获取信用核查报告详情
	 * @param taskId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getActDetailView.json")
	public RestServiceResult<Map> getActDetailView(String taskId, HttpServletRequest request) {
		RestServiceResult<Map> result = new RestServiceResult<Map>();
		Map<String,Object> map = new HashMap<String, Object>();

		RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ApplicationController#getActDetailView", "未获取到当前用户信息！");
				return result;
			}

			RestServiceResult<Integer> busId=xypjRemoteBaseService.getBusIdBuyTaskId(taskId);
			CheckReport checkReport=checkReportService.selectCheckReportInfo(busId.getData());
			
			String purpose_str=xypjRemoteBaseService.getDictByDtlKey("HCYT", checkReport.getPurpose()).getData().getDtlValue();
			checkReport.setPurpose_str(purpose_str);
			map.put("checkReport",checkReport);
			result.setData(map);
			return result;
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;

		}
	}
	
	/**
	 * 新增一个在线申请核查报告工作流
	 * @param applicant_unit 企业名称
	 * @param check_purpose 核查用途
	 * @param user_id 用户id
	 * @param username 用户名称
	 * @return
	 */
	@RequestMapping(value = "/addCheck.do")
	@ResponseBody
	public Object addCheck(@RequestParam(value = "ztmc", defaultValue = "", required = true) String ztmc,
			@RequestParam(value = "tyshxydm", defaultValue = "", required = true) String tyshxydm,
			@RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
			@RequestParam(value = "fddbr", defaultValue = "", required = true) String fddbr,
			@RequestParam(value = "lxr", defaultValue = "", required = true) String lxr,
			@RequestParam(value = "lxrdh", defaultValue = "", required = true) String lxrdh,
			@RequestParam(value = "yx", defaultValue = "", required = true) String yx,
			@RequestParam(value = "bz", defaultValue = "", required = true) String bz,
			@RequestParam(value = "purpose", defaultValue = "", required = true) String purpose,
			@RequestParam(value = "purpose_str", defaultValue = "", required = true) String purpose_str,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
			String token = HttpServletHelper.getUserXypjGatewayToken(request);
			if (StringUtils.isNotBlank(token)) {
				try {
					// 用户信息
					GatewayUserEntity user = gatewayAuthenticationService.getCurrentUserInfo(token);
					if (null != user && user.getId() > XypjConstants.NUMBER_ZERO) {
						Long userId=user.getId();
						int id = checkReportService.addCheck(ztmc,tyshxydm,tybm,fddbr,lxr,lxrdh,yx,bz,purpose,purpose_str,userId.intValue(),user.getUsername());
						String accessKey = UuidUtil.getUUid();
						xypjRemoteBaseService.addWorkFlow("resourceApplication",accessKey,0+"",null,id+"",
								"“" + ztmc + "”核查报告申请","","7",null);
						
					}
				} catch (Exception e) {
					ExceptionLogger.error(e);
					return result;
				}
			}else{
				return result;
			}
			return result;
	}
	
	/**
	 * 文件下载
	 *
	 * @param bgbh
	 *            规则id
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/download.json")
	@ResponseBody
	public void download(@RequestParam(value = "pdfpath", defaultValue = "", required = true) String pdfpath,
			HttpServletRequest request, HttpServletResponse response) {
		FileUtil.uploadFile(pdfpath, request, response);
	}
	
	/**
	 * 查看报告
	 *
	 * @param id
	 *            用户id
	 * @param bgbh
	 *            报告编号
	 * @return
	 */
	@RequestMapping(value = "/openReport.json")
	public void openReport(@RequestParam(value = "pdfpath", defaultValue = "", required = true) String pdfpath,
			HttpServletResponse response)
			throws IOException {

		response.setContentType("application/pdf");

		ServletOutputStream outputStream = response.getOutputStream();

		String ztmc=pdfpath.substring(pdfpath.lastIndexOf("/")+1);
		response.setHeader("Content-Disposition", "inline;fileName=" + ztmc);

		File pdf = null;
		FileInputStream fis = null;
		byte[] buffer = new byte[1024 * 1024];
		pdf = new File(pdfpath);
		response.setContentLength((int) pdf.length());
		fis = new FileInputStream(pdf);
		int readBytes = -1;
		while ((readBytes = fis.read(buffer, 0, 1024 * 1024)) != -1) {
			outputStream.write(buffer, 0, 1024 * 1024);
		}
		outputStream.close();
		fis.close();
	}
	
	/**
	 * 工作流页面获取信用核查报告详情
	 * @param taskId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCheckReportInfoList.json")
	public RestServiceResult<List<CheckReport>> selectCheckReportInfoList(
			@RequestParam(value = "condition", defaultValue = "") String condition,
			Page page,String checkStatus,String addTimeStart,String addTimeEnd,
			HttpServletRequest request) {
		RestServiceResult<List<CheckReport>> result = new RestServiceResult<List<CheckReport>>();
		String token = HttpServletHelper.getUserXypjGatewayToken(request);
		if (StringUtils.isNotBlank(token)) {
			try {
				// 用户信息
				GatewayUserEntity user = gatewayAuthenticationService.getCurrentUserInfo(token);
				String[] additionalColumns = { "id,pdfpath,check_status" };
				String[] configColumns = (String[]) MapCache.get(user.getId() + "_" + FRONT_TABLE_ID);
				List<String> showColumns = (configColumns == null || configColumns.length == 0)
						? ResourceCheckReportFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
				List<CheckReport> tableList = checkReportService.getByConditionForPage(showColumns, additionalColumns,
						condition, page, checkStatus,addTimeStart,addTimeEnd,(int)user.getId());
				result = new RestServiceResult<List<CheckReport>>(page.getTotalCount(), tableList);
			} catch (Exception e) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常！");
			}
		}else{
			return result;
		}
		
		return result;
	}
	
	/**
	 * 工作流页面获取信用核查报告详情
	 * @param taskId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCheckReportInfo.json")
	public RestServiceResult<CheckReport> selectCheckReportInfo(
			@RequestParam(value = "id", defaultValue = "") Integer id,
			
			HttpServletRequest request) {
		RestServiceResult<CheckReport> result = new RestServiceResult<CheckReport>();
		String token = HttpServletHelper.getUserXypjGatewayToken(request);
		if (StringUtils.isNotBlank(token)) {
			try {
				// 用户信息
				GatewayUserEntity user = gatewayAuthenticationService.getCurrentUserInfo(token);
						CheckReport checkReport = checkReportService.selectCheckReportInfo(id);
						result.setData(checkReport);
			} catch (Exception e) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常！");
			}
		}else{
			return result;
		}
		
		return result;
	}

	
	/**
	 * 工作流页面获取信用核查报告详情
	 * @param taskId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserInfoByUserId.json")
	public RestServiceResult<Map> selectUserInfoByUserId(HttpServletRequest request) {
		RestServiceResult<Map> result = new RestServiceResult<Map>();
		String token = HttpServletHelper.getUserXypjGatewayToken(request);
		if (StringUtils.isNotBlank(token)) {
			try {
				// 用户信息
				GatewayUserEntity user = gatewayAuthenticationService.getCurrentUserInfo(token);
				if (null != user && user.getId() > XypjConstants.NUMBER_ZERO) {
					Map m=checkReportService.selectUserInfoByUserId((int)user.getId());
					result.setData(m);
					
				}
			} catch (Exception e) {
				ExceptionLogger.error(e);
				return result;
			}
		}else{
			return result;
		}
		return result;
	}
	
	/**
	 * 工作流页面获取信用核查报告详情
	 * @param taskId
	 * @param request
	 * @return
	 */
	/**
	 * @param id
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserInfo.json")
	public RestServiceResult<Map> selectUserInfo(String id,HttpServletRequest request) {
		RestServiceResult<Map> result = new RestServiceResult<Map>();
		Map m=checkReportService.selectUserInfo(Integer.parseInt(id));
		result.setData(m);
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateCheckReport.do")
	public RestServiceResult<Map> updateCheckReport(String id,String checkTime,String checkStatus,String pdfpath,HttpServletRequest request) {
		RestServiceResult<Map> result = new RestServiceResult<Map>();
		checkReportService.updateCheckReport(Integer.parseInt(id),checkTime,checkStatus,pdfpath);
		result.setData(null);
		return result;
	}
}
